<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Random;
use think\Config;
use think\Validate;
use app\common\model\Third;
use app\admin\model\Area as AreaModel;
use app\admin\model\air\Airport as AirportModel;
use app\admin\model\air\Plane as PlaneModel;
use app\admin\model\air\Setting as SettingModel;
use app\admin\model\air\Charter as CharterModel;
use app\admin\model\air\JoinPlane as JoinModel;
use app\admin\model\air\Helpcat as CatModel;
use app\admin\model\air\HelpContent as ContentModel;
use Grafika\Grafika;
use Grafika\Color;

/**
 * 小程序接口
 */
class Mp extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    private $fontFile = '/template/mini/PingFang.ttc';
    private $fontFile1 = '/template/mini/PingFang_Medium_downcc.otf';
    // private $fontFile = '/template/mini/SourceHanSerifCN-VF.ttf';
    private $fontFileali = '/template/mini/alimamashuheiti.ttf';

    private $qrDir = '/uploads/shareimg';

    public function _initialize()
    {
        parent::_initialize();
        $allSettings = SettingModel::getSettings(); 
        $this->defaultPic = SettingModel::getSingleSetting('default_pic', $allSettings);
    }

    public function getAirPorts()
    {
        $airPorts = AirportModel::where('status', 'normal')->with('portarea')->select(); 
        $res = [];
        foreach ($airPorts as $ap) {
            $res[] = [
                'id' => $ap->id,
                'name'  => $ap->portarea->name,
                'lng' => $ap->lng,
                'lat' => $ap->lat,
            ];
        }

        $this->success('获取成功', $res);
    }

    public function getAirPortDetail()
    {
        $id = $this->request->get('id', 0);
        $detail = AirportModel::where('status', 'normal')->where('airport.id', $id)->with(['building', 'portarea'])->find();  
        if (!$detail) {
            $this->error('机场信息不存在!');
        }
        $detail->name = $detail->portarea->name;
        unset($detail->portarea);
        $detail->airport_image = getImg($detail->airport_image, $this->defaultPic);

        $this->success('获取成功', $detail);
    }

    public function getSalePlanes()
    {
        $data= PlaneModel::where('status', 'normal')->select(); 
        $res = [];
        foreach ($data as $d) {
            $res[] = [
                'img'  => getImg($d->banner_image, $this->defaultPic),
                'name' => $d->name,
                'id' => $d->id,
            ];
        }
        $this->success('获取成功', $res);
    
    }

    public function getPlaneDetail()
    {
        $id = $this->request->get('id', 0);
        $detail = PlaneModel::where('status', 'normal')->where('id', $id)->find();  
        if (!$detail) {
            $this->error('飞机信息不存在!');
        }

        $detail->detail_image = cdnurl($detail->detail_image, true);
        $images = empty($detail->detail_images) ? [] : explode(",", $detail->detail_images);
        foreach ($images as &$img) {
            $img = cdnurl($img, true);
        }
        unset($img);
        $detail->detail_images = $images;
        $images = empty($detail->cabin_images) ? [] : explode(",", $detail->cabin_images);
        foreach ($images as &$img) {
            $img = cdnurl($img, true);
        }
        unset($img);
        $detail->cabin_image = $images;
        unset($detail->cabin_images);

        $detail->special = json_decode($detail->special_str, true);
        $detail->delivery = json_decode($detail->delivery_str, true);
        $detail->motor = json_decode($detail->motor_str, true);
        $detail->sail = json_decode($detail->sail_str, true);

        $this->success('获取成功', $detail);
    
    }

    public function getCharters()
    {
        $model = new \app\admin\model\air\Charter;
        $units = $model->getUnitList();
        $curDate = date('Y-m-d');
        $data= CharterModel::where('status', 'normal')
          ->where('end_date', '>=', $curDate)
          ->with(['scity', 'ecity'])
          ->order('start_date', 'asc')->select(); 
        $res = [];
        foreach ($data as $d) {
            $res[] = [
                'img'  => getImg($d->banner_image),
                'plan_name' => $d->plan_name,
                // 'price' => round($d->price / 10000, 1),
                'price' => number_format($d->price),
                'unit' => $units[$d->unit],
                'sit_total' => $d->sit_total,
                'start_date' => date('m月d日', strtotime($d->start_date)),
                'end_date' => date('m月d日', strtotime($d->end_date)),
                'start_date_ori' => $d->start_date,
                'end_date_ori' => $d->end_date,
                'start_city' => empty($d->scity) ? '未知' : $d->scity->shortname,
                'end_city' => empty($d->ecity) ? '未知' : $d->ecity->shortname,
                'start_city_id' => $d->start_area_id,
                'end_city_id' => $d->end_area_id,
                'flight_time' => changeMins($d->flight_time),
                'order_status' => $d->order_status,
                'id' => $d->id,
            ];
        }
        $this->success('获取成功', $res);
    }

    public function getCharterDetail()
    {
        $model = new \app\admin\model\air\Charter;
        $units = $model->getUnitList();
        $id = $this->request->get('id', 0);
        $detail = CharterModel::where('charter.status', 'normal')
          ->with(['scity', 'ecity'])
          ->where('charter.id', $id)->find();  
        if (!$detail) {
            $this->error('飞机信息不存在!');
        }
        $detail->flight_time_str = changeMins($detail->flight_time);
        unset($detail->flight_time);

        $detail->start_date = date('m月d日', strtotime($detail->start_date));
        $detail->end_date = date('m月d日', strtotime($detail->end_date));

        $detail->start_city = !empty($detail->scity) ? $detail->scity->shortname : '未知';
        $detail->end_city = !empty($detail->ecity) ? $detail->ecity->shortname : '未知';

        $detail->banner_image = cdnurl($detail->banner_image, true);
        $images = empty($detail->detail_images) ? [] : explode(",", $detail->detail_images);
        foreach ($images as &$img) {
            $img = cdnurl($img, true);
        }
        unset($img);
        $detail->detail_images = $images;
        $images = empty($detail->cabin_images) ? [] : explode(",", $detail->cabin_images);
        foreach ($images as &$img) {
            $img = cdnurl($img, true);
        }
        unset($img);
        $detail->cabin_image = $images;
        unset($detail->cabin_images);

        $detail->special = json_decode($detail->special_str, true);
        $detail->delivery = json_decode($detail->delivery_str, true);
        $detail->motor = json_decode($detail->motor_str, true);
        $detail->sail = json_decode($detail->sail_str, true);

        $service = json_decode($detail->service_str, true);
        $detail->service = $this->outputImg($service);

        $plant = json_decode($detail->plant_str, true);
        $detail->plant = $this->outputImg($plant);
        $food = json_decode($detail->food_str, true);
        $detail->food = $this->outputImg($food);
        $fun = json_decode($detail->fun_str, true);
        $detail->fun = $this->outputImg($fun);
        $detail->unit = $units[$detail->unit];
        $detail->price = number_format($detail->price);

        $this->success('获取成功', $detail);
    
    }

    public function getJoins()
    {
        $curDate = date('Y-m-d');
        $data= JoinModel::where('status', 'normal')
          ->where('end_date', '>=', $curDate)
          ->with(['scity', 'ecity'])
          ->order('start_date', 'asc')
          ->select(); 
        $res = [];
        foreach ($data as $d) {
            if (empty($d->end_date)) {
                $d->end_date = $d->start_date;
            }
            $res[] = [
                'img'  => getImg($d->plane_image),
                'start_date' => date('m月d日', strtotime($d->start_date)),
                'start_date_ori' => $d->start_date,
                'end_date' => date('m月d日', strtotime($d->end_date)),
                'end_date_ori' => $d->end_date,
                'start_city' => empty($d->scity) ? '未知' : $d->scity->shortname,
                'end_city' => empty($d->ecity) ? '未知' : $d->ecity->shortname,
                'price' => $d->price_str,
                'min_total' => $d->min_total,
                'max_total' => $d->max_total,
                'id' => $d->id,
            ];
        }
        $this->success('获取成功', $res);
    }

    public function helps()
    {
        $cats = CatModel::where('status', 'normal')->with('contents')->select();    

        $this->success('获取成功', $cats);
    }

    public function getInCity()
    {
        $areas = AreaModel::where('area_type', '1')
                ->where('level', '2')
                ->where('in_out', '1')->order('first', 'asc')->select();
        $hotCity = [];
        $chars = [];
        $charCity = [];
        $charData = [];
        foreach ($areas as $a) {
            $a = [
                'id' => $a['id'],
                'name' => $a['name'],
                'shortname' => $a['shortname'],
                'first' => $a['first'],
                'is_hot' => $a['is_hot']
            ];
            if ($a['is_hot']) {
                $hotCity[] = $a;
            }
            if (!isset($charData[$a['first']])) {
                $charData[$a['first']] = [];
            }
            $charData[$a['first']][] = $a;
        }

        foreach ($charData as $char => $citys) {
            if (!empty($char)) {
                $chars[] = $char;
                $charCity[] = [
                    'char' => $char,
                    'citys' => $citys,
                ];
            }
        }

        $res = [
            'hot_city'  => $hotCity,
            'chars' => $chars,
            'charCity' => $charCity,
        ];

        $this->success('获取成功', $res);
    }

    public function getOutCity()
    {
        // 录入时需要按顺序，先国家后城市
        $areaModel = AreaModel::where('area_type', '1')
                ->where('in_out', '2')->select();
        $hotCity = [];
        $areas = [];
        $country = [];
        $countryCity = [];
        foreach ($areaModel as $a) {
            $a = [
                'id' => $a['id'],
                'name' => $a['name'],
                'shortname' => $a['shortname'],
                'first' => $a['first'],
                'is_hot' => $a['is_hot'],
                'pid' => $a['pid'],
                'level' => $a['level'],
            ];
            if ($a['is_hot']) {
                $hotCity[] = $a;
            }
            if ($a['level'] == '1' && !isset($areas[$a['id']])) {
                $areas[$a['id']] = [
                    'name' => $a['shortname'],
                    'id' => $a['id'],
                    'country' => [],
                ];
            }

            if ($a['level'] == '2' && !isset($country[$a['id']])) {
                $country[$a['id']] = [
                    'name' => $a['shortname'],
                    'id' => $a['id'],
                    'pid' => $a['pid'],
                    'city' => [],
                ];
            }

            if ($a['level'] == '3') {
                $country[$a['pid']]['city'][] = $a;
            }
        }
        // 处理未按顺序录入的
        $noIds = [];
        $noCity = [];
        foreach ($country as $countryId => $c)  {
            if (!isset($c['pid'])) {
                if (!in_array($c['city'][0]['pid'], $noIds)) {
                    $noIds[] = $c['city'][0]['pid'];
                    $noCity[$c['city'][0]['pid']] = $c;
                }
            }
            if (isset($c['pid']) && isset($areas[$c['pid']])) {
                $areas[$c['pid']]['country'][] = $c;
            }
        }
        $areaModel = AreaModel::where('area_type', '1')
                ->where('id', 'in', $noIds)
                ->where('in_out', '2')->select();
        $country = [];
        foreach ($areaModel as $a) {
            $country[$a['id']] = [
                'name' => $a['shortname'],
                'id' => $a['id'],
                'pid' => $a['pid'],
                'city' => $noCity[$a['id']]['city'],
            ];
        }
        foreach ($country as $countryId => $c)  {
            if (isset($c['pid']) && isset($areas[$c['pid']])) {
                $areas[$c['pid']]['country'][] = $c;
            }
        }

        $areaData = [];
        foreach ($areas as $pid => $p) {
            if (!empty($p['country'])) {
                $areaData[] = $p;
            }
        }

        $res = [
            'hot_city'  => $hotCity,
            'area_data' => $areaData,
        ];

        $this->success('获取成功', $res);
    
    }

    public function searchAirport()
    {
        $k = $this->request->get('k', '');
        if (empty($k)) {
            $this->success('获取成功', []);
        }
        $areaModel = AreaModel::where('area.name', 'like', '%'.$k.'%')
                ->where('area.area_type', '2')
                ->with('parea')
                ->select();
        $city = [];
        $cityIds = [];
        foreach ($areaModel as $area) {
            $cityIds[] = $area['parea']['id'];
            if (!isset($city[$area['pid']])) {
                $city[$area['pid']] = [];
            }
            $city[$area['pid']][] = [
                'id' => $area->id,
                'airport_name' => $area->name,
                'airport_shortname' => $area->shortname,
                'airport_3' => $area->airport_3,
                'airport_4' => $area->airport_4,
            ];
        }
        $cityIds = array_unique($cityIds);
        if (empty($cityIds)) {
            $areaModel = AreaModel::where('name', 'like', '%'.$k.'%')
                    ->where('area_type', '1')
                    ->select();
            foreach ($areaModel as $area) {
                $cityIds[] = $area['id'];
            }
        }

        $areaModel = AreaModel::where('area.id', 'in', $cityIds)
          ->where('area.area_type', '1')
          ->where('(area.level = 2 and area.in_out=1) or (area.level = 3 and area.in_out=2)')->with('parea')->select();
        $cityInfos = [];
        foreach ($areaModel as $area) {
            $cityInfos[$area['id']] = [
                'id' => $area->id,
                'city_name'  => $area->name,
                'city_shortname' => $area->shortname,
                'area_code'  => $area->area_code,
                'belong_name' => $area->parea->name,
                'airports' => isset($city[$area['id']]) ? $city[$area['id']] : [],
            ];
        }

        $res = [];
        foreach ($cityInfos as $cityId => $c) {
            $res[] = $c;
        }
        $this->success('获取成功', $res);
         
    }

    public function shareCharter()
    {
        $id = $this->request->get('id'); 
        $detail = CharterModel::where('status', 'normal')
          ->with(['scity', 'ecity'])
          ->where('charter.id', $id)->find();  
        if (!$detail) {
            $this->error('特惠包机信息不存在!');
        }
        $model = new \app\admin\model\air\Charter;
        $units = $model->getUnitList();
        // 获取起飞落地信息
        $scity = $detail->scity->shortname;
        $ecity = $detail->ecity->shortname;
        $startDate = date('m月d日', strtotime($detail->start_date));
        $endDate = date('m月d日', strtotime($detail->end_date));
        $planeName = $detail->plan_name;
        $sitTotal = $detail->sit_total;
        $price = $detail->price;
        $underPrice = $detail->underline_price;
        $unit = $units[$detail->unit];
        /*
        $scity = '北京北京';
        $ecity = '天津天津天天际';
        */
        // $price = 10000;
        // $underPrice = 1000;
        $shareImg = $this->createShareImg($scity, $ecity, $startDate, $endDate, $planeName, $sitTotal, $price, $underPrice, $unit);
        $this->success('success', ['share_img' =>cdnurl($shareImg, true)]);
    }

    private function createShareImg($scity, $ecity, $startDate, $endDate, $planeName, $sitTotal, $price, $underPrice, $unit)
    {
        $curPath = dirname(dirname(APP_PATH));
        $editor = Grafika::createEditor();
        $outDestDir = $curPath . $this->qrDir;
        $this->createDir($outDestDir);
        $shareCode = uniqid();
        // $shareCode = 'test';
        $outFile = $outDestDir . '/' . 'share_'.$shareCode.'.jpg';
        $bs = 2;
        try {
            // 素材图
            $bgFile = '/template/mini/share_bg.png';
            $miniCodeImg = '/template/mini/mini_code.jpg';

            $editor->open($bgImage, $curPath . $bgFile);

            $editor->open($miniImage, $curPath . $miniCodeImg);
            $editor->resize($miniImage, 75*$bs, 73*$bs);

            $editor->blend($bgImage, $miniImage, 'normal', 1, 'top-left', 248 * $bs, 433 * $bs);
            
            $sizeText = 28;
            $lineHeight = 12;
            $yTextInit = 230;
            // 出发地或目的地超过5个字的时候
            if (mb_strlen($scity) > 5 || mb_strlen($ecity) > 5) {
                $yText = ($yTextInit - 10)  * $bs;
            } else {
                $yText = $yTextInit * $bs;
            }
            $textWidth = 180;
            $textStart = 20 * $bs;

            $text = $scity;
            if (mb_strlen($scity) > 5) {

                $text = $this->autowrap($sizeText, 0, $curPath . $this->fontFile, $text, $textWidth) ;
                $texts = explode(PHP_EOL, $text);

                foreach ($texts as $k => $t) {
                    $editor->text($bgImage , $t, $sizeText, $textStart, $yText + $k * $lineHeight + $k * $sizeText, new Color("#1A1C1E"), $curPath . $this->fontFile);
                    $editor->text($bgImage , $t, $sizeText, $textStart + 1, $yText + $k * $lineHeight + $k * $sizeText, new Color("#1A1C1E"), $curPath . $this->fontFile);
                }
            } else {
                $editor->text($bgImage , $text, $sizeText, $textStart, $yText,new Color("#1A1C1E"), $curPath . $this->fontFile);
                $editor->text($bgImage , $text, $sizeText, $textStart+1, $yText,new Color("#1A1C1E"), $curPath . $this->fontFile);
            }

            $textStart = 276;
            $textLen= mb_strlen($ecity);
            if ($textLen >= 3) {
                // 超过5个字时，按5个字算起始写的位置
                if ($textLen > 5) {
                    $textLen = 5;
                }
                $textStart = $textStart - ($sizeText-8) * ($textLen - 2);
            }
            $textStart = $textStart * $bs;
            $text = $ecity;
            if (mb_strlen($ecity) > 5) {

                $text = $this->autowrap($sizeText, 0, $curPath . $this->fontFile, $text, $textWidth) ;
                $texts = explode(PHP_EOL, $text);

                foreach ($texts as $k => $t) {
                    $editor->text($bgImage , $t, $sizeText, $textStart, $yText + $k * $lineHeight + $k * $sizeText, new Color("#1A1C1E"), $curPath . $this->fontFile);
                    $editor->text($bgImage , $t, $sizeText, $textStart + 1, $yText + $k * $lineHeight + $k * $sizeText, new Color("#1A1C1E"), $curPath . $this->fontFile);
                }
            } else {
                $editor->text($bgImage , $text, $sizeText,$textStart, $yText,new Color("#1A1C1E"), $curPath . $this->fontFile);
                $editor->text($bgImage , $text, $sizeText,$textStart + 1, $yText,new Color("#1A1C1E"), $curPath . $this->fontFile);
            }

            // 日期
            $sizeText = 24;
            $lineHeight = 12;
            $yText = 308 * $bs;

            $textStart = 114 * $bs;
            if ($startDate == $endDate) {
                $text = $startDate;
            } else {
                $text = $startDate . " - " . $endDate;
            }
            $editor->text($bgImage , $text, $sizeText,$textStart, $yText,new Color("#1A1C1E"), $curPath . $this->fontFile);

            // 机型名称
            $sizeText = 22;
            $lineHeight = 12;
            $yText = 370 * $bs;

            $textStart = 116 * $bs;
            $text = $planeName . " | " . $sitTotal . "座";
            $editor->text($bgImage , $text, $sizeText,$textStart, $yText,new Color("#1A1C1E"), $curPath . $this->fontFile);
            $editor->text($bgImage , $text, $sizeText,$textStart + 1, $yText,new Color("#1A1C1E"), $curPath . $this->fontFile);

            // 价格字
            $sizeText = 14;
            $lineHeight = 12;
            $yText = 455 * $bs;
            /*
            $textStart = 15 * $bs;
            $text =  "¥";
            $editor->text($bgImage , $text, $sizeText,$textStart, $yText,new Color("#4365DE"), $curPath . $this->fontFile);
            $editor->text($bgImage , $text, $sizeText,$textStart + 1, $yText,new Color("#4365DE"), $curPath . $this->fontFile);
             */

            // 价格 
            $sizeText = 28;
            $lineHeight = 12;
            $yText = 449 * $bs;

            $textStart = 20 * $bs;
            $text =  number_format($price);
            $editor->text($bgImage , $text, $sizeText,$textStart, $yText,new Color("#4365DE"), $curPath . $this->fontFile);
            $editor->text($bgImage , $text, $sizeText,$textStart + 1, $yText,new Color("#4365DE"), $curPath . $this->fontFile);

            // 人民币 
            $sizeText = 22;
            $lineHeight = 12;
            $yText = 449 * $bs;
            
            if ($price >= 1000000) { 
                $textStart = 108 * $bs;
            } else if ($price >= 100000) {
                $textStart = 98 * $bs;
            } else {
                $textStart = 88 * $bs;
            }
            $text =  $unit;
            $editor->text($bgImage , $text, $sizeText,$textStart, $yText,new Color("#686868"), $curPath . $this->fontFile);
            
            /*
            // 划线价格 
            $sizeText = 18;
            $lineHeight = 12;
            $yText = 451 * $bs;
            
            // 跟在上面的后面 
            $textStart = $textStart + 100;
            $text =  $underPrice . "元";
            $editor->text($bgImage , $text, $sizeText,$textStart, $yText,new Color("#BCBCBC"), $curPath . $this->fontFile);

            // _
            $str = str_repeat("_", mb_strlen($underPrice) + 1);
            $sizeText = 16;
            $lineHeight = 12;
            $yText = 448 * $bs;
            
            // 跟在上面的后面 
            $text =  $str;
            $editor->text($bgImage , $text, $sizeText,$textStart, $yText,new Color("#BCBCBC"), $curPath . $this->fontFile);
             */

            $editor->save($bgImage, $outFile);

        } catch(\Exception $e) {
            echo $e->getMessage();
            $outFile = '';
        }

        return str_replace($curPath, '', $outFile);

    }

    private function createDir($destDir)
    {
        if (!is_dir($destDir)) {
            @mkdir($destDir, 0755, true);
        }
    }

    private function autowrap($fontsize, $angle, $fontface, $string, $width)
    {
        // 参数分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
        $content = "";
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        preg_match_all("/./u", $string, $arr);
        $letter = $arr[0];
        foreach($letter as $l) {
            $teststr = $content.$l;
            $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
            if (($testbox[2] > $width) && ($content !== "")) {
                $content .= PHP_EOL;
            }
            $content .= $l;
        }
        return $content;
    }

    private function autocenter($fontsize, $angle, $fontface, $string, $width)
    {
        $testbox = imagettfbbox($fontsize, $angle, $fontface, $string);
        $textWidth = $testbox[2] - $testbox[0];
        $startx = ceil(($width -  $textWidth) / 2);

        return $startx;
    }

    private function outputImg($fields)
    {
        $preImg = '/assets/charter_img/%s.png';
        $data = [];
        foreach ($fields as $s) {
            $s['img'] = cdnurl(sprintf($preImg, $s['field']), true);
            if ($s['state']) {
                $data[] = $s;
            }
        }

        return $data;
    }
}
